import configparser
import json

from flask import Flask, make_response
# from flask_docs import ApiDoc
from flask_siwadoc import SiwaDoc

from db.db_help import DBHelp
from model.base_model import MyBaseModel
from router import account_router, blog_router

app = Flask(__name__)
siwa = SiwaDoc()
if __name__ == '__main__':
    DBHelp.conn()
    file = 'config/config.ini'
    con = configparser.ConfigParser()
    con.read(file, encoding='utf-8')
    server_address = con.items('server_address')
    project = con.items('project')
    server_address = dict(server_address)
    project = dict(project)
    host = (server_address.get('host'), int(server_address.get('port')))
    # 使用Flask架设服务
    app.register_blueprint(account_router.bp)
    app.register_blueprint(blog_router.bp)
    # 配置ApiDoc
    app.config["API_DOC_MEMBER"] = []
    app.config["API_DOC_AUTO_GENERATING_ARGS_MD"] = True
    for item in app.blueprints.items():
        app.config["API_DOC_MEMBER"].append(item[0])
    # ApiDoc(
    #     app,
    #     title="Sample App",
    #     version="1.0.0",
    #     description="11A simple app API",
    # )
    siwa = SiwaDoc(title="siwadocapi", description="一个自动生成openapi文档的库", openapi_url="/open.json",
                   version="1.0.0")
    siwa.init_app(app)
    # 启动服务
    app.run(host=server_address.get('host'), port=int(server_address.get('port')), debug=True)
    print(f"服务器启动成功, 服务地址:http://%s:%s" % host)


@app.errorhandler(404)
def show_404_page(cls, e):
    response = make_response(json.dumps(
        MyBaseModel(code=404, msg="404路由不存在").__dict__,
        ensure_ascii=False,
    ).encode(encoding="utf-8"), 404)
    response.content_type = "application/json"
    return response


#
@app.errorhandler(500)
def show_500_page(cls, e):
    response = make_response(json.dumps(
        MyBaseModel(code=500, msg="服务器出错").__dict__,
        ensure_ascii=False,
    ).encode(encoding="utf-8"), 500)
    response.content_type = "application/json"
    return response
